package com.yanftch.stopcoding.common.network

import com.yanftch.stopcoding.common.util.LogUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
import javax.imageio.ImageIO

class ImageLoader {
    private val TAG = "debug_ImageLoader"

    private val client = OkHttpClient()

    suspend fun loadImage(url: String): ImageResult? {
        return try {
            // 1. 优先使用 OkHttp 请求图片
            val response = withContext(Dispatchers.IO) {
                val request = Request.Builder().url(url).build()
                client.newCall(request).execute()
            }

            if (response.isSuccessful) {
                response.body?.byteStream()?.use { inputStream ->
                    val realUrl = response.request.url.toString()
                    val image = ImageIO.read(inputStream)
                    if (image != null) {
                        LogUtil.d(TAG, "loadImageWithOkHttp success: realUrl=$realUrl")
                        return ImageResult(image, realUrl) // OkHttp 请求成功，返回图片和重定向后的 URL
                    }
                }
            }
            // 如果 OkHttp 请求失败，尝试使用 ImageIO 请求
            loadImageWithImageIO(url)

        } catch (e: IOException) {
            e.printStackTrace()
            LogUtil.d(TAG, "loadImageWithOkHttp failed, try load with ImageIO   $e")
            // OkHttp 请求失败，尝试使用 ImageIO
            loadImageWithImageIO(url)
        }
    }

    // 2. 如果 OkHttp 失败，则使用 ImageIO 加载
    private fun loadImageWithImageIO(url: String): ImageResult? {
        return try {
            val image = ImageIO.read(java.net.URL(url))
            LogUtil.d(TAG, "loadImageWithImageIO success????: image=$image,     url=$url")
            if (image != null) {
                ImageResult(image, url) // 使用 ImageIO 加载成功
            } else {
                null // ImageIO 加载失败
            }
        } catch (e: IOException) {
            e.printStackTrace()
            LogUtil.d(TAG, "loadImageWithImageIO failed$e")
            null // 捕获异常，返回 null
        }
    }
}
